<?php
/*
Template Name: Gestione Categorie
*/
/*
2015 03 14 : add -> drag & drop effect
2015 03 10 : add -> run only if registred user
*/
session_start();
include('classe_resize.php');
include('localfunctions.php');
?>
<script type="text/javascript">

var stile = "top=10, left=10, width=680, height=400, status=no, menubar=no, toolbar=no, scrollbars=yes";

window.onload = reminde_focus;
function reminde_focus(event){
	document.sottocategoria.nome_cat.focus();
	return false;
}

function deleteAlert(id){
	var conBox = confirm("Sicuro di voler eliminare la sottocategoria?");
	if(conBox)
		if (confirm('Verranno cancellati tutti i prodotti di questa sottocategoria!\nProseguire?')) 
			location.href="<?php echo $_SESSION['PHP_SELF'];?>?&id="+ id + "&mode=remove";
		else
			return;
	else
		return;
	
}
function set_focus(){
	if (document.form_inserisci.selezione.value == "Seleziona categoria") {
		alert("Selezionare una categoria.");
		document.form_inserisci.selezione.focus();
	return false;
	}
}

</script>
<style type="text/css">
<!--
.Stile38 {
	font-size: 14px;
	color: #FFFFFF;
	font-weight: bold;
}
-->
</style>
<?php get_header(); global $wpdb; ?>
<script type="text/javascript" src=<?php echo '"'.get_template_directory_uri().'/js/jquery-drag-n-drop/jquery-ui-1.7.1.custom.min.js">'; ?> </script>


<script type="text/javascript">
$(document).ready(function(){ 			   
	$(function() {
		$("#contentLeft tbody").sortable({ opacity: 0.6, cursor: 'move', update: function() {
			var order = $(this).sortable("serialize") + '&action=updateRecordsListings'; 
			$.post("<?php echo get_template_directory_uri().'/js/jquery-drag-n-drop/updateDB.php'?>", order, function(theResponse){
				$("#contentRight").html(theResponse);
			}); 															 
		}								  
		});
	});

});	
</script>
			<?php get_sidebar('top'); ?>
			<table width="100%" border="0" cellspacing="0" cellpadding="5">
  				<tr>
    				<td colspan="0" valign="top"><font color="#193E52" size="+2" face="Arial, Helvetica, sans-serif"><b><?php echo theme_get_meta_option($post->ID, 'theme_show_page_title') ? get_the_title() : ''?></b></font></td>
  				</tr>
			</table>

<?php
if (is_user_logged_in()) {
$path = WP_CONTENT_DIR."/uploads/";


if(isset($_POST['inserisci']) && $_POST['inserisci']=='Aggiungi'){
	if(isset($_FILES)&&($_FILES['img_cat']['name'] != "")){
    	$immagine = $_FILES['img_cat']['name'];
		$caratteri = array(" ","'","(",")","[","]","/","_");
		$immagine = str_replace($caratteri,"",$immagine);
		$immagine = strtolower($immagine);
		$rating = $_POST['rating'];
		
		Upload_Resize_new($path,$immagine,$_FILES['img_cat']['tmp_name']);
		
		
		$categorie = array("gemme"=>1,"gemme taglio double rose" => 2, "gioielli taglio double rose"=>3);
		$selezione = $categorie[$_POST['selezione']];
		$campi=array("categoria"=>$selezione,"nome"=>$_POST['nuova_cat'],"img"=>$immagine, "rating"=>$rating);
		
		if( $wpdb->insert($wpdb->prefix.'subcat_preziosi',$campi) )
			echo "<script>alert('Inserita nuova sottocategoria!')</script>";
		else
			echo "<script>alert('ERRORE: Sottocategoria non inserita!')</script>";
	}else{
		$categorie = array("gemme"=>1,"gemme taglio double rose" => 2, "gioielli taglio double rose"=>3);
		$selezione = $categorie[$_POST['selezione']];
		$campi=array("categoria"=>$selezione,"nome"=>$_POST['nuova_cat'], "rating"=>$_POST['rating']);
		
		if( $wpdb->insert($wpdb->prefix.'subcat_preziosi',$campi) )
			echo "<script>alert('Inserita nuova sottocategoria!')</script>";
		else
			echo "<script>alert('ERRORE: Sottocategoria non inserita!')</script>";	
	}
}

if(isset($_GET['id'])){
	$id_elimina=$_GET['id'];
	if($_GET['mode'] == "remove")
		if( $wpdb->query("DELETE FROM {$wpdb->prefix}subcat_preziosi WHERE id = '$id_elimina'") )
			echo "<script> alert(\"CANCELLAZIONE DELLA SOTTO-CATEGORIA ESEGUITA CON SUCCESSO\") </script>";
		else
			echo "<script> alert(\"ERRORE: CANCELLAZIONE DEI PRODOTTI DELLA SOTTO-CATEGORIA NON AVVENUTA!\") </script>";
}

if(isset($_POST['id_cat']) && isset($_POST['nome_cat']) && isset($_POST['modifica_cat'])){
	if(isset($_FILES)&&($_FILES['img_cat']['name'] != "")){
    	$immagine = $_FILES['img_cat']['name'];
		$caratteri = array(" ","'","(",")","[","]","/","_");
		$immagine = str_replace($caratteri,"",$immagine);
		$immagine = strtolower($immagine);
		Upload_Resize($path,$immagine,$_FILES['img_cat']['tmp_name']);
		$id_modifica = $_POST['id_cat'];
		$nome_cat = $_POST['nome_cat'];
		$rating = $_POST['rating'];

		if($wpdb->query("UPDATE {$wpdb->prefix}subcat_preziosi SET nome = '$nome_cat', img = '$immagine', rating='$rating' WHERE id = '$id_modifica'"))
			echo "<script> alert(\"Modifca effettuata!\")</script>";
		else
			echo "<script> alert(\"ERRORE: Modifica (con foto) non avvenuta!\")</script>";		
	}else{
	
		$id_modifica = $_POST['id_cat'];
		$nome_cat = $_POST['nome_cat'];
		$rating = $_POST['rating'];
		
		if($wpdb->query("UPDATE {$wpdb->prefix}subcat_preziosi SET nome = '$nome_cat', rating='$rating' WHERE id = '$id_modifica'"))
			echo "<script> alert(\"Modifca effettuata!\")</script>";
		else
			echo "<script> alert(\"ERRORE: Modifica non avvenuta!\")</script>";
	}
}

$cat_sql = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}cat_preziosi");

?>
<table width="100%" border="1" cellpadding="0" cellspacing="0" bordercolor="#0C3062">
	<tr>
		<td valign="top" >
        	<!-- Inizio ciclo esterno -->
            <?php 
				foreach ( $cat_sql as $cat ){
			?>
			<table width="100%" border="0" cellpadding="2" cellspacing="0" style="border:0px" id="contentLeft" > 
				<thead>
					<tr> <!-- INIZIO RIGA DI INTESTAZIONE -->
						<td colspan="2" width="50%" height="21" bgcolor="#174E9B" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid">
							<span class="Stile38" style="margin-left:2px"><?php echo $cat->nome; ?></span>
						</td>
						<td colspan="2" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid; align-text:center;"><strong>Aggiungi Sottocategoria Gemme </strong></td>
					</tr> <!-- FINE RIGA DI INTESTAZIONE -->
				</thead>	
				<tbody >
			    <!-- Inizio ciclo interno -->
                <?php
				$i=1;
						$subcat_sql = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}subcat_preziosi WHERE categoria = '$cat->id' ORDER BY rating ASC");
						foreach ( $subcat_sql as $subcat ){
				?>
					<tr >
						<td  valign="top" bgcolor="#F1F1F1"  >
							<!-- <table width="100%" border="0" cellspacing="0" cellpadding="0"> <!-- INIZIO TABELLA SOTTOCATEGORIE -->
								<tr id="recordsArray_<?php echo $subcat->id?>">
									<td width="10%"  background="<?php bloginfo('template_url');?>/images/bgtab3.png" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid; padding-right:5px; ">
                                    <?php echo $subcat->rating; ?>
									</td>
									<td width="20%" height="21" background="<?php bloginfo('template_url');?>/images/bgtab3.png" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid">
									<?php
										if((!isset($_POST['modifica']) || $_POST['modifica'] == 'no') || ($_POST['modifica']=='Modifica' && $subcat->id != $_POST['id_campo']))
									?>
											<img src="<?php echo network_home_url(); ?>/wp-content/uploads/lista/lista/thumbnails/<?php echo "thumb_".$subcat->img; ?>" height="20px" style="max-width:20px">

									</td>                            
									<td width="40%" height="21" background="<?php bloginfo('template_url');?>/images/bgtab3.png" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid">
                                	<?php
										if((!isset($_POST['modifica']) || $_POST['modifica'] == 'no') || ($_POST['modifica']=='Modifica' && $subcat->id != $_POST['id_campo']))
											echo ucfirst($subcat->nome);
										if($_POST['id_campo']==$subcat->id){
									?>
                                    
										<input type="text" name="nome_cat" value="<?php echo $subcat->nome; ?>" size="10"/>
                                        <input type="hidden" name="id_cat" value="<?php echo $subcat->id; ?>" />
										<input type="file" name="img_cat" style="width:190px"/>
                                        <input type="submit" name="modifica_cat" value="Salva"/>
                                        <input type="reset" name="reset_cat" value="Annulla" onclick="location.href='<?php echo "http://".$_SERVER['HTTP_HOST'].$_SERVER['REDIRECT_URL']; ?>'"/>
									</form>
                                    <?php
										}
									?>							
									</td>
									<td height="21" background="<?php bloginfo('template_url');?>/images/bgtab3.png" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid">
                                	<form action="<?php echo "http://".$_SERVER['HTTP_HOST'].$_SERVER['REDIRECT_URL']; ?>" name="modifica_form" method="post" >
										<input type="submit" name="modifica" value="Modifica" style="height:21px" />
                                        <input type="hidden" name="id_campo" value="<?php echo $subcat->id; ?>" />
                                        <input type="button" name="Elimina" value="Elimina" style="height:21px" onClick="javascript:deleteAlert('<?php echo $subcat->id;?>');"/>
                                    </form>
									</td>
								</tr>
							<!-- </table> <!-- FINE TABELLA SOTTOCATEGORIE -->                
						</td>
					</tr>
                <!-- Fine ciclo interno -->
                <?php
						}
				?>
				</tbody>
				<td colspan="2" style="height:21px">&nbsp;</td>  
			</table>
            <!-- Fine ciclo esterno -->
            <?php
				}
			?>
		</td>
	</tr>
</table>

<p>quando elimini una categoria ti deve uscire una popup chiedendoti se sei sicuro di voler cancellare la categoria, se premi si ti deve uscire un'altra popun che ti deve comunicare che cancellando la categoria andranno anche cancellati i prodotti associati a quella categoria... continuare ? si o no ? </p>
<table width="100%" border="1" cellpadding="0" cellspacing="0" bordercolor="#006600">
  <tr>
    <td valign="top" bgcolor="#f1f1f1">
    <table width="100%" border="0" cellpadding="2" cellspacing="0" style="border:0px">
      <tr>
        <td height="21" bgcolor="#006600" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid"><span class="Stile38" style="margin-left:2px">Aggiungi Sottocategoria </span></td>
        </tr>
      <tr>
        <td valign="top" bgcolor="#F1F1F1">
        <table width="100%" border="0" cellspacing="2" cellpadding="2">   
        <form action="<?php echo "http://".$_SERVER['HTTP_HOST'].$_SERVER['REDIRECT_URL']; ?>" method="post" name="form_inserisci" onsubmit="return set_focus();" enctype="multipart/form-data">
          <tr>
            <td width="323" height="21" valign="top" background="<?php bloginfo('template_url');?>/images/bgtab3.png" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid">
            Categoria di appartenenza </td>
            <td  height="21" valign="top" background="<?php bloginfo('template_url');?>/images/bgtab3.png" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid">
            <label>
              <select name="selezione" style="height:21px">
              <option selected="selected">Seleziona categoria</option>
              <?php
			  	foreach($cat_sql as $cat)
	                echo "<option>".$cat->nome."</option>";
			  ?>
              </select>
            </label></td>
          </tr>
          <tr>
            <td  height="21" valign="top" background="<?php bloginfo('template_url');?>/images/bgtab3.png" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid">
            Nome Sottocategoria </td>
            <td  height="21" valign="top" background="<?php bloginfo('template_url');?>/images/bgtab3.png" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid">
            <label>
              <input name="nuova_cat" type="text" / style="height:21px" size="50" />
            </label>
            </td>
          </tr>
          <tr>
            <td  height="21" valign="top" background="<?php bloginfo('template_url');?>/images/bgtab3.png" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid">Immagine</td>
            <td  height="21" valign="top" background="<?php bloginfo('template_url');?>/images/bgtab3.png" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid">
            <label>
              <input name="img_cat" type="file" / style="height:21px" size="50" />
            </label>
            </td>
          </tr> 
          <tr>
            <td  height="21" valign="top" background="<?php bloginfo('template_url');?>/images/bgtab3.png" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid">Rating</td>
            <td  height="21" valign="top" background="<?php bloginfo('template_url');?>/images/bgtab3.png" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid">
            <label>
              <input name="rating" type="text" disabled value="1000" type="text" STYLE="color: #FFFFFF; font-family: Verdana; font-weight: bold; font-size: 12px; background-color: #72A4D2;"/ style="height:21px" size="50" />
            </label>
            </td>
          </tr>          
          <tr>
            <td  height="21" valign="top" background="<?php bloginfo('template_url');?>/images/bgtab3.png" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid">&nbsp;</td>
            <td  height="21" valign="top" background="<?php bloginfo('template_url');?>/images/bgtab3.png" style="border-bottom:#666666; border-bottom-width:1px; border-bottom-style:solid">
            <input type="submit" name="inserisci" value="Aggiungi" / style="height:21px" /></td>
          </tr>
          </form>
        </table></td>
      </tr>
    </table>
    </td>
  </tr>
</table>
<p>&nbsp;</p>
<p align="center">&nbsp;</p>
				<?php get_sidebar('bottom'); ?>
<div id="contentRight">
</div>
<?php } else 
	{?>
	<div style="font-size: xx-large;font-weight: bold;margin-top: 20px;">
		Restricted area, please login
	</div>
	<?php
	}

get_footer(); ?>